package org.hongqi.common.senpec.person.certification.batch;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.RequiredArgsConstructor;
import org.hongqi.common.senpec.base.utils.SymbolSwitcher;
import org.hongqi.common.senpec.person.certification.Certification;
import org.hongqi.common.senpec.person.certification.CertificationMapper;
import org.hongqi.common.senpec.sys.user.User;
import org.hongqi.common.senpec.sys.user.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;
import java.util.UUID;

@Component
@RequiredArgsConstructor
public class CertificationBatchListener implements ReadListener<CertificationBatch> {

    private final UserMapper userMapper;
    private final CertificationMapper certificationMapper;
    private final Collection<Certification> certifications = new HashSet<>();

    @Override
    public void invoke(CertificationBatch data, AnalysisContext context) {
        Certification certification = new Certification();
        BeanUtils.copyProperties(data, certification);
        certifications.add(certification);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = userMapper.selectByUsername(username);
        certifications.forEach(certification -> {
            if (certification.getId() == null) {
                certification.setCreator(user.getId());
                certification.setUpdater(user.getId());
                certification.setAttachmentUuid(UUID.randomUUID().toString());
                certification.setMethod(SymbolSwitcher.certificationMethodSwitcherR(certification.getMethodStr()));
                certificationMapper.insert(certification);
            } else {
                certification.setUpdater(user.getId());
                certificationMapper.updateById(certification);
            }
        });
        certifications.clear();
    }
}
